// https://ext.dcloud.net.cn/plugin?id=594

declare var plus: any; // 由于 `plus` 是 UniApp 特有的对象，可以声明为 `any` 类型

let isIos: boolean;
// #ifdef APP-PLUS
isIos = uni.getSystemInfoSync().platform == "ios";
// #endif

// 判断推送权限是否开启
function judgeIosPermissionPush(): boolean {
  let result = false;
  // #ifdef APP-PLUS
  const UIApplication = plus.ios.import("UIApplication");
  const app = UIApplication.sharedApplication();
  let enabledTypes = 0;

  if (app.currentUserNotificationSettings) {
    const settings = app.currentUserNotificationSettings();
    enabledTypes = settings.plusGetAttribute("types");
    console.log("enabledTypes1:" + enabledTypes);
    if (enabledTypes === 0) {
      console.log("推送权限没有开启");
    } else {
      result = true;
      console.log("已经开启推送功能!");
    }
    plus.ios.deleteObject(settings);
  } else {
    enabledTypes = app.enabledRemoteNotificationTypes();
    if (enabledTypes === 0) {
      console.log("推送权限没有开启!");
    } else {
      result = true;
      console.log("已经开启推送功能!");
    }
    console.log("enabledTypes2:" + enabledTypes);
  }

  plus.ios.deleteObject(app);
  plus.ios.deleteObject(UIApplication);
  // #endif
  return result;
}

// 判断定位权限是否开启
function judgeIosPermissionLocation(): boolean {
  let result = false;
  // #ifdef APP-PLUS
  const cllocationManger = plus.ios.import("CLLocationManager");
  const status = cllocationManger.authorizationStatus();
  result = status !== 2;
  console.log("定位权限开启：" + result);
  plus.ios.deleteObject(cllocationManger);
  // #endif
  return result;
}

// 判断麦克风权限是否开启
function judgeIosPermissionRecord(): boolean {
  let result = false;
  // #ifdef APP-PLUS
  const avaudiosession = plus.ios.import("AVAudioSession");
  console.log(avaudiosession);
  const avaudio = avaudiosession.sharedInstance();
  const permissionStatus = avaudio.recordPermission();
  console.log("permissionStatus", permissionStatus);
  if (permissionStatus === 1684369017 || permissionStatus === 1970168948) {
    console.log("麦克风权限没有开启");

    // uni.showModal({
    //   title: "温馨提示",
    //   content: "请前往设置打开权限",
    //   confirmText: "确认",
    //   cancelText: "取消",
    //   success: async (r) => {
    //     if (r.confirm) {
    //       gotoAppPermissionSetting();
    //     }
    //   },
    // });
  } else {
    result = true;
    console.log("麦克风权限已经开启,1735552628");
  }
  plus.ios.deleteObject(avaudiosession);
  // #endif
  return result;
}

// 判断相机权限是否开启
function judgeIosPermissionCamera(): boolean {
  let result = false;
  // #ifdef APP-PLUS
  const AVCaptureDevice = plus.ios.import("AVCaptureDevice");
  const authStatus = AVCaptureDevice.authorizationStatusForMediaType("vide");
  console.log("authStatus:" + authStatus);
  if (authStatus === 3) {
    result = true;
    console.log("相机权限已经开启");
  } else {
    console.log("相机权限没有开启");
  }
  plus.ios.deleteObject(AVCaptureDevice);
  // #endif
  return result;
}

// 判断相册权限是否开启
function judgeIosPermissionPhotoLibrary(): boolean {
  let result = false;
  // #ifdef APP-PLUS
  const PHPhotoLibrary = plus.ios.import("PHPhotoLibrary");
  const authStatus = PHPhotoLibrary.authorizationStatus();
  console.log("authStatus:" + authStatus);
  if (authStatus === 3) {
    result = true;
    console.log("相册权限已经开启");
  } else {
    console.log("相册权限没有开启");
  }
  plus.ios.deleteObject(PHPhotoLibrary);
  // #endif
  return result;
}

// 跳转到**应用**的权限页面
function gotoAppPermissionSetting(): void {
  // #ifdef APP-PLUS
  console.log(isIos);
  if (isIos) {
    const UIApplication = plus.ios.import("UIApplication");
    const application2 = UIApplication.sharedApplication();
    const NSURL2 = plus.ios.import("NSURL");
    const setting2 = NSURL2.URLWithString("app-settings:");
    application2.openURL(setting2);

    plus.ios.deleteObject(setting2);
    plus.ios.deleteObject(NSURL2);
    plus.ios.deleteObject(application2);
  } else {
    const Intent = plus.android.importClass("android.content.Intent");
    const Settings = plus.android.importClass("android.provider.Settings");
    const Uri = plus.android.importClass("android.net.Uri");
    const mainActivity = plus.android.runtimeMainActivity();
    const intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    const uri = Uri.fromParts("package", mainActivity.getPackageName(), null);
    intent.setData(uri);
    mainActivity.startActivity(intent);
  }
  // #endif
}

// Android权限查询
function requestAndroidPermission(permissionID: string): Promise<number> {
  return new Promise((resolve, reject) => {
    plus.android.requestPermissions(
      [permissionID], // 理论上支持多个权限同时查询，但实际上本函数封装只处理了一个权限的情况。可扩展
      function (resultObj: any) {
        let result = 0;
        for (let i = 0; i < resultObj.granted.length; i++) {
          const grantedPermission = resultObj.granted[i];
          console.log("已获取的权限：" + grantedPermission);
          result = 1;
        }
        for (let i = 0; i < resultObj.deniedPresent.length; i++) {
          const deniedPresentPermission = resultObj.deniedPresent[i];
          console.log("拒绝本次申请的权限：" + deniedPresentPermission);
          result = 0;
        }
        for (let i = 0; i < resultObj.deniedAlways.length; i++) {
          const deniedAlwaysPermission = resultObj.deniedAlways[i];
          console.log("永久拒绝申请的权限：" + deniedAlwaysPermission);
          result = -1;
        }
        resolve(result);
        // 如果权限被拒绝，可以打开APP设置界面
        if (result === -1) {
          uni.showModal({
            title: "温馨提示",
            content: "请前往设置打开权限",
            confirmText: "确认",
            cancelText: "取消",
            success: async (r) => {
              if (r.confirm) {
                gotoAppPermissionSetting();
              }
            },
          });
        }
      },
      function (error: any) {
        console.log("申请权限错误：" + error.code + " = " + error.message);
        resolve({
          code: error.code,
          message: error.message,
        });
      }
    );
  });
}

export {
  judgeIosPermissionPush,
  judgeIosPermissionLocation,
  judgeIosPermissionRecord,
  judgeIosPermissionCamera,
  judgeIosPermissionPhotoLibrary,
  gotoAppPermissionSetting,
  requestAndroidPermission,
};
